package cn.masterj.springcloud.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.masterj.springcloud.entity.Order;
import cn.masterj.springcloud.mapper.OrderMapper;
import cn.masterj.springcloud.service.IAccountService;
import cn.masterj.springcloud.service.IOrderService;
import cn.masterj.springcloud.service.IStorageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author masterJ
 * @create 2020-04-20 17:33
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Autowired
    private IStorageService storageService;

    @Autowired
    private IAccountService accountService;


    /**
     * 测试 seata 的全局事物
     * @return
     */
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public Order create() {
        // 1、 插入订单记录，状态 -1 未完成状态
        Order order = new Order();
        order.setNum(1);
        order.setProductId(1L);
        order.setSerial(IdUtil.fastSimpleUUID());
        order.setStatus(-1);
        save(order);
        // 2、 远程调用 减库存
        storageService.decrease(1L);

        // 3、 远程调用 扣金额
        accountService.payment(1L);

        // 4、 更新订单记录，状态 0 已完成状态
        order.setStatus(0);
        updateById(order);
        return order;
    }
}
